<?php
/**
 * Plugin Theme Handling.
 *
 * @package WP cr mobile
 */
class CRMobile_Theme
{
    private static $instance  = false;
    private static $themePath = '';

    /**
     * Singleton class
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        self::$themePath = WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.
            'wp-cr-mobile'.DIRECTORY_SEPARATOR.
            'themes'.DIRECTORY_SEPARATOR;
    }

    public static function getThemes()
    {
        $themes = self::parseDirectory(self::$themePath);
        
        if (CRMobile_Admin::validLicense()) {
            $premium = self::parseDirectory(
                self::$themePath.'_premium'.DIRECTORY_SEPARATOR,
                '_premium/'
            );
            $themes = array_merge($themes, $premium);
            asort($themes);
        }

        return $themes;
    }

    public static function getForm($company)
    {
        $content = self::loadFile(
            self::$themePath.$company->theme.DIRECTORY_SEPARATOR.'form.php',
            $company
        );

        // Replace variables
        $themeUrl = WP_PLUGIN_URL.'/wp-cr-mobile/themes/'.$company->theme;
        $content = str_replace('{{intro_text}}', stripslashes($company->intro), $content);
        $content = str_replace('{{theme_url}}', $themeUrl, $content);
        $content = str_replace('{{company_name}}', stripslashes($company->name), $content);
        $content = str_replace('{{company_url}}', $company->url, $content);
        $content = str_replace('{{logo_url}}', $company->logo, $content);

        $content = str_replace('{{form}}', self::generateForm($company), $content);
        return $content;
    }

    public static function getThanks($company, $rating, $review)
    {
        $content = self::loadFile(
            self::$themePath.$company->theme.DIRECTORY_SEPARATOR.'thanks.php',
            $company,
            $rating
        );

        // Replace variables
        $themeUrl = WP_PLUGIN_URL.'/wp-cr-mobile/themes/'.$company->theme;
        $content = str_replace('{{intro_text}}', stripslashes($company->intro), $content);
        $content = str_replace('{{thankyou_text}}', self::selectText($company->thanks, $rating, 'thanks_'), $content);
        $content = str_replace('{{theme_url}}', $themeUrl, $content);
        $content = str_replace('{{company_name}}', stripslashes($company->name), $content);
        $content = str_replace('{{company_url}}', $company->url, $content);
        $content = str_replace('{{coupon_url}}', $company->coupon, $content);
        $content = str_replace('{{share}}', self::shareButtons($company, $review), $content);
        $content = str_replace('{{logo_url}}', $company->logo, $content);
        $social = unserialize($company->social);
        $content = str_replace('{{facebook_url}}', $social['facebook'], $content);
        $content = str_replace('{{twitter_url}}', $social['twitter'], $content);
        $content = str_replace('{{google_url}}', $social['google'], $content);
        return $content;
    }

    public static function shareButtons($company, $review)
    {
        $assets = plugins_url("assets/", CRMobile::FILE);
        $url = urlencode($company->url);
        $title = urlencode($company->name);
        $review = urlencode($review);

        $share = "<a href='http://www.facebook.com/sharer.php?m2w&s=100&p[title]={$title}&p[summary]={$review}&p[url]={$url}'><img src='{$assets}share-facebook.png' /></a>";
        $share .= "<a href='http://twitter.com/share?text={$review}&url={$url}'><img src='{$assets}share-twitter.png' /></a>";
        $share .= "<a href='https://m.google.com/app/plus/x/?v=compose&content={$review}%20{$url}'><img src='{$assets}share-google.png' /></a>";

        return $share;
    }

    public static function selectText($texts, $rating, $prefix)
    {
        $texts = unserialize($texts);

        // Find the texts that are active
        foreach ($texts as $key => $value) {
            if ($value !== '') {

                $activeTexts[] = substr($key, -1);
            }
        }

        // Choose text closes to rating
        if (empty($activeTexts)) {
            return;
        }
        $index = self::closest($activeTexts, $rating);
        $txt = $texts[$prefix.$index];

        return stripslashes($txt);
    }

    public static function closest($array, $number)
    {
        sort($array);
        foreach ($array as $a) {
            if ($a >= $number) return $a;
        }
        return end($array); // or return NULL;
    }

    public static function loadFile($file, $company, $rating = 0)
    {
        ob_start();
        $logo = (strlen($company->logo) > 0) ? true : false;
        if (self::endsWith($file, 'thanks.php')) {
            $coupon = (strlen($company->coupon) > 0) ? true : false;
            $sharing = ($company->sharing != 0 and $rating >= $company->sharing) ? true : false;

            $temp = unserialize($company->social);
            $social_facebook = ($temp['facebook'] !== '') ? true : false;
            $social_twitter = ($temp['twitter'] !== '') ? true : false;
            $social_google = ($temp['google'] !== '') ? true : false;
            $social = ($social_facebook or $social_twitter or $social_google)
                ? true
                : false;
            unset($temp);
        }
        include($file);
        return ob_get_clean();
    }

    public static function generateForm($company)
    {
        $exclude = unserialize($company->exclude);
        $data = array(
            'id'    => $company->ID,
            'slug'  => CRMobile_MobileSite::slugify($company->name),
            'email' => $exclude['email'],
            'sms'   => $company->sms
        );
        return CRMobile_View::render(
            plugin_dir_path(__FILE__).'../../views/mobile-form.php',
            $data
        );
    }

    public static function parseDirectory($dir, $prefix = '')
    {
        $results = scandir($dir);

        foreach ($results as $result) {
            if ($result === '.' or $result === '..' or $result === '_premium') {
                continue;
            }

            if (is_dir($dir . '/' . $result)) {
                $themes[$prefix.$result] = ucwords(str_replace('-', ' ', $result));
            }
        }

        return $themes;
    }

    public static function endsWith($haystack, $needle)
    {
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }

        return (substr($haystack, -$length) === $needle);
    }
}
